<template>
  <div class="media-list-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>媒资管理</el-breadcrumb-item>
      <el-breadcrumb-item>全部媒资</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 操作工具栏 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="searchForm.deptId" placeholder="请选择部门" clearable>
            <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.mediaType" placeholder="请选择媒资类型" clearable>
            <el-option v-for="type in mediaTypeList" :key="type.code" :label="type.name" :value="type.code"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.categoryId" placeholder="请选择一级分类" clearable>
            <el-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable>
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 15px;">
        <el-col :span="24" style="text-align: right;">
          <el-button type="primary" @click="handleCreate">添加媒资</el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
          <el-dropdown @command="handleBatchOperation">
            <el-button>批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="audit">批量审核</el-dropdown-item>
                <el-dropdown-item command="publish">批量上线</el-dropdown-item>
                <el-dropdown-item command="unpublish">批量下线</el-dropdown-item>
                <el-dropdown-item command="share">批量分享</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-card>

    <!-- 媒体列表表格 -->
    <el-card class="list-card" style="margin-top: 20px;">
      <el-table
        v-loading="loading"
        :data="mediaList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="缩略图" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.coverUrl"
              :src="scope.row.coverUrl"
              :preview-src-list="[scope.row.coverUrl]"
              style="width: 60px; height: 40px;"
            ></el-image>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200"></el-table-column>
        <el-table-column prop="mediaType" label="媒资类型" width="100">
          <template #default="scope">
            {{ getMediaTypeText(scope.row.mediaType) }}
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120"></el-table-column>
        <el-table-column prop="deptName" label="部门" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" style="margin-top: 20px; text-align: right;">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { mediaApi } from '../../api/media.js'

// 响应式数据
const loading = ref(false)
const mediaList = ref([])
const deptList = ref([])
const mediaTypeList = ref([])
const categoryList = ref([])
const selectedRows = ref([])

// 搜索表单
const searchForm = ref({
  deptId: '',
  mediaType: '',
  categoryId: '',
  keyword: ''
})

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 初始化数据
onMounted(() => {
  initData()
  fetchMediaList()
})

// 初始化基础数据
const initData = async () => {
  try {
    const [deptRes, typeRes, categoryRes] = await Promise.all([
      mediaApi.getDeptList(),
      mediaApi.getMediaTypeList(),
      mediaApi.getCategoryList({ level: 1 })
    ])
    deptList.value = deptRes.data || []
    mediaTypeList.value = typeRes.data || []
    categoryList.value = categoryRes.data || []
  } catch (error) {
    ElMessage.error('初始化数据失败')
    console.error('初始化数据失败:', error)
  }
}

// 获取媒体列表
const fetchMediaList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm.value,
      pageNum: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    }
    const res = await mediaApi.getMediaList(params)
    mediaList.value = res.data?.list || []
    pagination.value.total = res.data?.total || 0
  } catch (error) {
    ElMessage.error('获取媒体列表失败')
    console.error('获取媒体列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchMediaList()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  fetchMediaList()
}

const handleCurrentChange = (current) => {
  pagination.value.currentPage = current
  fetchMediaList()
}

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 创建媒体
const handleCreate = () => {
  // 跳转到创建页面
  window.location.href = '/#/media/create'
}

// 查看媒体
const handleView = (row) => {
  window.location.href = `/#!/media/detail/${row.id}`
}

// 编辑媒体
const handleEdit = (row) => {
  window.location.href = `/#!/media/edit/${row.id}`
}

// 删除媒体
const handleDelete = async (id) => {
  try {
    await mediaApi.deleteMedia(id)
    ElMessage.success('删除成功')
    fetchMediaList()
  } catch (error) {
    ElMessage.error('删除失败')
    console.error('删除失败:', error)
  }
}

// 批量删除
const handleBatchDelete = async () => {
  const ids = selectedRows.value.map(row => row.id)
  try {
    await mediaApi.batchDeleteMedia(ids)
    ElMessage.success('批量删除成功')
    fetchMediaList()
  } catch (error) {
    ElMessage.error('批量删除失败')
    console.error('批量删除失败:', error)
  }
}

// 批量操作
const handleBatchOperation = async (command) => {
  const ids = selectedRows.value.map(row => row.id)
  if (ids.length === 0) {
    ElMessage.warning('请先选择要操作的媒体')
    return
  }

  try {
    switch (command) {
      case 'audit':
        await mediaApi.auditMedia(ids, 1) // 1表示审核通过
        ElMessage.success('批量审核成功')
        break
      case 'publish':
        await mediaApi.publishMedia(ids, 1) // 1表示上线
        ElMessage.success('批量上线成功')
        break
      case 'unpublish':
        await mediaApi.publishMedia(ids, 0) // 0表示下线
        ElMessage.success('批量下线成功')
        break
      case 'share':
        ElMessage.success('分享功能开发中...')
        break
    }
    fetchMediaList()
  } catch (error) {
    ElMessage.error('操作失败')
    console.error('批量操作失败:', error)
  }
}

// 获取媒资类型文本
const getMediaTypeText = (typeCode) => {
  const type = mediaTypeList.value.find(t => t.code === typeCode)
  return type ? type.name : typeCode
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已审核',
    2: '审核驳回',
    3: '已上线',
    4: '已下线'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'danger',
    3: 'primary',
    4: 'warning'
  }
  return typeMap[status] || 'info'
}
</script>

<style scoped>
.media-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
}
</style>